/**
 * common.js
 * 
 * @since 1.0 <2015-12-5> SoChishun <14507247@qq.com> Added.
 */

// 免费字体资源:http://www.fontsquirrel.com 2015-12-4 SoChishun Added.
$(document).ready(function () {
    // 消息滚动播放插件 2015-12-4 SoChishun Added.
    // see:http://www.rjboy.cn/?p=708
    if ('undefined' !== typeof ($.fn.Xslider)) {
        load_notices(true);
        setInterval(load_notices, 10000); // 10秒重载一次
    }
    // 布局渲染 2015-12-3 SoChishun Added.
    // see:http://layout.jquery-dev.com/index.cfm
    if ('undefined' !== typeof ($.fn.layout)) {
        $('body').layout({
            applyDemoStyles: true,
            spacing_open: 2, //边框的间隙
            spacing_closed: 6, //关闭时边框的间隙
            resizerTip: '可调整大小', //鼠标移到边框时，提示语
            sliderTip: "显示/隐藏面板", //在某个Pane隐藏后，当鼠标移到边框上显示的提示语。
            togglerTip_open: "关闭", //pane打开时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerTip_closed: "打开", //pane关闭时，当鼠标移动到边框上按钮上，显示的提示语  
            togglerLength_open: 150, //pane打开时，边框按钮的长度  
            togglerLength_closed: 300, //pane关闭时，边框按钮的长度,
        }).allowOverflow('north'); // 允许下拉菜单越过框架范围而不出现滚动条
    }

// 菜单点击，添加到访问历史
    $('.menu-link').click(function () {
        var id = $(this).data('id');
        return MenuHistory.add(id);
    })
    $('.menu-tabs li a:first-child').click(function () {
        var id = $(this).parent().data('id');
        MenuHistory.active(id);
    })
    $('.menu-tabs .xsui-btn-refresh').click(function () {
        location.reload();
    })
    $('.menu-tabs .xsui-btn-close').click(function () {
        var id = $(this).parent().data('id');
        id = MenuHistory.remove(id);
        location.href = $('.menu-tabs [data-id="' + id + '"] a:first-child').attr('href');
    })
    // 导航菜单下拉设置
    if ('undefined' !== typeof ($.fn.superfish)) {
        $('ul.sf-menu').superfish({delay: 100});
    }
    // 侧边栏菜单展开和收起 2015-12-3 SoChishun Added.
    $('.aside-menu legend a').click(function () {
        $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent().next().toggle();
    })
    // 表单fieldset的展开和收起 2016-2-2 SoChishun Added.    
    $('legend .xsui-switch').click(function () {
        $(this).text('[-]' == $(this).text() ? '[+]' : '[-]').parent().next('.xsui-switch-content').toggle();
        return false;
    })
    // 设置侧边栏菜单状态
    set_aside_menu_status();
    $('.user-zone .switch').click(function () {
        var $p = $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent();
        $p.find('legend').toggle();
        $p.find('.content').toggle();
    })
    $('.clock-zone .switch').click(function () {
        $(this).find('i').toggleClass('fa-toggle-on').toggleClass('fa-toggle-off').parent().parent().next().toggle();
    })
    // 日历功能 2015-12-4 SoChishun Added.
    $('#calendar').datepicker({showWeek: true, autoSize: true});
    // 设置日期选择器
    $(".datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        showWeek: true
    });
    // 设置时间日期选择器 see:http://trentrichardson.com/examples/timepicker/
    if ('undefined' !== typeof ($.fn.datetimepicker)) {
        $('.datetimepicker').datetimepicker({
            currentText: '现在',
            closeText: '确定',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            secondText: '秒钟',
            showSecond: true,
            changeMonth: true,
            changeYear: true,
            timeFormat: "HH:mm:ss",
            altFormat: "yy-mm-dd",
            altTimeFormat: "HH:mm:ss",
            showWeek: true
        });
        $('.datetimepicker-hm').datetimepicker({
            currentText: '现在',
            closeText: '确定',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            showSecond: false,
            changeMonth: true,
            changeYear: true,
            altFormat: "yy-mm-dd",
            altTimeFormat: "h:m t",
            showWeek: true
        });
        $('.timepicker').timepicker({
            timeOnlyTitle: '选择时间',
            currentText: '现在',
            closeText: '确定',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            secondText: '秒钟',
            timeFormat: "HH:mm:ss",
        });
        $('.timepicker-hm').timepicker({
            timeOnlyTitle: '选择时间',
            currentText: '现在',
            closeText: '确定',
            timeText: '时间',
            hourText: '小时',
            minuteText: '分钟',
            timeFormat: "HH:mm",
        });
    }
    /**
     * 时钟功能
     * @returns {undefined}
     * @since 1.0 <2015-12-4> SoChishun Added.
     * @since VER:1.1; DATE:2016-1-18; AUTHOR:SoChishun; DESC:修正日期错误
     * @example <div id="clock"><span title="">----------------- ---:---:---</span><i class="fa fa-sun-o" title=""></i></div>
     *      setInterval(clock, 1000);
     */
    function clock() {
        var d = new Date(); // 测试 new Date(2015,12,4,22,0,0)
        var week = ['天', '一', '二', '三', '四', '五', '六'];
        var odate = {'y': d.getFullYear(), 'm': d.getMonth() + 1, 'd': d.getDate(), 'h': d.getHours(), 'i': d.getMinutes(), 's': d.getSeconds()};
        var sdate = odate.y + '-' + (odate.m < 10 ? '0' + odate.m : odate.m) + '-' + (odate.d < 10 ? '0' + odate.d : odate.d);
        var stime = sdate + ' ' + (odate.h < 10 ? '0' + odate.h : odate.h) + ':' + (odate.i < 10 ? '0' + odate.i : odate.i) + ':<em>' + (odate.s < 10 ? '0' + odate.s : odate.s) + '<em>';
        var sdateinfo = '今天是' + sdate + ', 星期' + week[d.getDay()] + ', 第' + d.getWeekOfYear() + '周';
        var swords = [[2, 5, '亲，您还在工作吗？熬夜伤身，赶紧休息哦~'], [5, 6, '您这么早就来啦，现在还是凌晨哦！'], [8, 12, '一日之计在于晨，好好加油哦！'], [12, 13, '享受一顿丰盛的午餐然后美美睡个午觉，为下午的工作补充能量~'], [14, 16, '激情工作中，燃烧吧，小宇宙！'], [17, 18, '准备下班啦，赶紧把手头的工作做个收尾哦~'], [20, 22, '亲，加班呀，辛苦啦...'], [22, 23, '夜深了，您还没休息吗，保重身体哦~']];
        var sword = '';
        for (var i in swords) {
            if (odate.h >= swords[i][0] && odate.h < swords[i][1]) {
                sword = swords[i][2];
                break;
            }
        }
        $('#clock').find('i').removeClass('fa-sun-o').removeClass('fa-moon-o').addClass(odate.h >= 18 ? 'fa-moon-o' : 'fa-sun-o').attr('title', sword);
        $('#clock').find('span').html(stime).attr('title', sdateinfo); // 收起展示
    }
    setInterval(clock, 1000);
    // 点击菜单,保存到访问历史中
    $('.main-menu, .aside-menu a').click(function () {
        var id = $(this).data('id');
    })

    // 设置可视化编辑器,控件不能加属性 require
    if ("undefined" !== typeof KindEditor) {
        if (undefined == window.config || undefined == window.config.KINDEDITOR_UPLOADER) {
            alert('未设置上传处理页面!');
        } else {
            // 按钮属性查看 http://kindeditor.net/docs/option.html
            KindEditor.create('.editor', {
                uploadJson: window.config.KINDEDITOR_UPLOADER,
                allowFileManager: false,
                autoHeightMode: true,
                items: [
                    'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'wordpaste', 'plainpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'table', 'insertorderedlist',
                    'insertunorderedlist', '|', 'emoticons', 'baidumap', '|', 'image', 'multiimage', 'insertfile', 'link', 'unlink', '|', 'print', 'source', 'fullscreen']
            });
            KindEditor.create('.pm-editor', {
                uploadJson: window.config.KINDEDITOR_UPLOADER,
                allowFileManager: false,
                autoHeightMode: true,
                items: [
                    'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
                    'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', '|', 'table', 'insertorderedlist',
                    'insertunorderedlist', '|', 'emoticons', 'baidumap', '|', 'image', 'insertfile', 'link', 'unlink']
            });
        }
    }
});

// 设置侧边栏选中状态 2016-1-29 SoChishun Added.
function set_aside_menu_status() {
    var cur = $('.aside-menu').data('current');
    if (!cur) {
        return;
    }
    $('.aside-menu').find('a').each(function () {
        var $a = $(this);
        if ($a.attr('href').indexOf('/' + cur + '/') > -1) {
            $a.parent().addClass('current');
        }
    })
}
/**
 * 加载公告内容
 * @param {type} first
 * @returns {undefined}
 * @since VER:1.0; DATE:2016-2-3; AUTHOR:SoChishun; DESC:Added.
 */
function load_notices(first) {
    var $list = $('#slider-content-list');
    var url = $list.data('url');
    var href = $list.data('href');
    if (!url || !href) {
        return;
    }
    $list.html('');
    $.post(url, function (data) {
        if (!data) {
            return;
        }
        var str = '';
        for (var i in data) {
            str += '<li><a href="' + href.replace('varkey', data[i].id) + '" target="_blank" title="' + data[i].title + '">' + data[i].title + '</a></li>';
        }
        $list.html(str);
        if (first) {
            notices_slider_init();
        }
    })
}
/**
 * 初始化公告滚动插件
 * @returns {undefined}
 * @since VER:1.0; DATE:2016-2-3; AUTHOR:SoChishun; DESC:Added.
 */
function notices_slider_init() {
    $(".notices-slider").Xslider({
        unitdisplayed: 1,
        numtoMove: 1,
        loop: "cycle",
        dir: "V",
        autoscroll: 2500,
        speed: 300
    });
}
/**
 * 计算当前日期在本年度的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 4)).getWeekOfYear(); // 当前日期是本年度第几周
 (new Date(2015, 11, 31)).getWeekOfYear(); // 2015 年度有几周(注意：JS 中月的取值范围为 0~11)
 */
Date.prototype.getWeekOfYear = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;

    var year = this.getFullYear();
    var firstDay = new Date(year, 0, 1);
    var firstWeekDays = 7 - firstDay.getDay() + weekStart;
    var dayOfYear = (((new Date(year, this.getMonth(), this.getDate())) - firstDay) / (24 * 3600 * 1000)) + 1;
    return Math.ceil((dayOfYear - firstWeekDays) / 7) + 1;
}

/**
 * 计算当前日期在本月份的周数
 * @param {Number} weekStart 每周开始于周几：周日：0，周一：1，周二：2 ...，默认为周日
 * @returns {Number}
 * @since 1.0 <2015-12-4> by http://blog.csdn.net/orain/article/details/7063273
 * @example
 (new Date(2015, 11, 31)).getWeekOfMonth(); // 当前日期是本月第几周(注意：JS 中月的取值范围为 0~11)
 (new Date(2015, 0, 31)).getWeekOfMonth(); // 2015年度1月有几周
 */
Date.prototype.getWeekOfMonth = function (weekStart) {
    weekStart = (weekStart || 0) - 0;
    if (isNaN(weekStart) || weekStart > 6)
        weekStart = 0;

    var dayOfWeek = this.getDay();
    var day = this.getDate();
    return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
}

/**
 * 菜单访问历史
 * [1.0 SoChishun 2015-12-11]
 * @type type
 * @version
 *  VER1.0 AT:2015-12-07 BY:SoChishun Email:14507247@qq.com DESC:Added.
 */
var MenuHistory = {
    cookie_key: 'menu_history',
    read: function () {
        // 需要Cookies插件支持,请到https://github.com/js-cookie/js-cookie下载该插件
        if ('undefined' == typeof (Cookies)) {
            return;
        }
        var sdata = Cookies.get(this.cookie_key);
        return sdata ? JSON.parse(sdata) : false;
    },
    save: function (odata) {
        Cookies.set(this.cookie_key, JSON.stringify(odata));
    },
    /**
     * 激活标签
     * [1.0 SoChishun 2015-12-07]
     * @param {type} id
     * @returns {undefined}
     * @version
     *  VER1.0 AT:2015-12-07 BY:SoChishun Email:14507247@qq.com DESC:Added.     * 
     */
    active: function (id) {
        if (!id) {
            return;
        }
        var odata = this.read();
        if (!odata) {
            return;
        }
        odata.cur = id;
        this.save(odata);
    },
    add: function (id) {
        if (!id) {
            return false;
        }
        // {cur:0,'ids':[1,2,3...]}
        var odata = this.read();
        if (!odata) {
            odata = {cur: id, ids: [id]};
        } else {
            odata.cur = id;
            if (odata.ids.indexOf(id) < 0) {
                if (10 < odata.ids.push(id)) {
                    odata.ids.shift();
                }
            }
        }
        this.save(odata);
        return true;
    },
    /**
     * 删除标签,返回新标签id
     * @param {type} id
     * @returns {odata@arr;ids}
     */
    remove: function (id) {
        if (!id) {
            return id;
        }
        var odata = this.read();
        if (!odata) {
            return id;
        }
        var i = odata.ids.indexOf(id);
        if (i > -1) {
            odata.ids.splice(i, 1);
            var len = odata.ids.length;
            if (i > len - 1) {
                i = len - 1;
            }
            id = odata.ids[i];
            odata.cur = id;
        }
        this.save(odata);
        return id;
    }
};

// 动态更改排序 2016-1-18
// 如：<td class="sort"><input type="text" value="$vo.sort" size="3" data-value="$vo.sort" data-url="AddonU('change_sort','id='.$vo['id'].'&sort=varsort')" title="更改后,鼠标点击页面任意位置即可自动生效" /></td>
function change_sort($input) {
    var old_v = $input.data('value');
    if ($input.val() == old_v) {
        return;
    }
    $.get($input.data('url').replace('varsort', $input.val()), function (data) {
        if ('string' == typeof (data)) {
            data = JSON.parse(data);
        }
        if (data.status) {
            location.reload();
        } else {
            $('<div>' + data.info + '</div>').dialog();
        }
    })

}